<?php

Yii::import("adviser.components.ProjectHelper");

class ReportController extends Controller {
	/**
	 * @var string the default layout for the views. Defaults to 'column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = 'application.views.layouts.column2';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	public $project;

	public function init() {
		parent::init();
		if (isset ($_GET['project_id'])) {
			$this->project = Project::model()->findByPk($_GET['project_id']);
			if ($this->project != null)
			$this->layout = 'project';
		}

		if (isset ($_GET['ajax'])) {
			if ($_GET['ajax'])
			$this->layout = 'ajax';
		}
	}

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array (
			'ShowProject + view,list',
			'EditProject + create,update,delete',
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function filterShowProject($filterChain)
	{
		$project = Project::model()->findByPk($_GET['id']);
		if (!ProjectHelper::canReadProject($project))
		{
			throw new CHttpException(403,'Access Denied');
		}
		$filterChain->run();
	}

	public function filterEditProject($filterChain)
	{
		$project = Project::model()->findByPk($_GET['project_id']);
		if (!ProjectHelper::canEditProject($project))
		{
			throw new CHttpException(403,'Access Denied');
		}
		$filterChain->run();
	}


	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array (
		array (
				'allow', // allow all users to perform 'index' and 'view' actions
				'expression' => 'true'
				),
				array (
				'deny', // deny all users
				'users' => array (
					'*'
					),


					),

						
					);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView() {
		$this->render('view', array (
			'model' => $this->loadModel(),

			
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
		$model = new EditedReport;
		$project = null;
		$report = null;
		$parameters = array ();
		$model->edition_date = date("Y-m-d H:i:s");
		$model->edition_user = Yii::app()->user->id;

		if (isset ($_GET['project_id'])) {
			$model->project_id = $_GET['project_id'];

			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);

			$project = Project::model()->findByPk($model->project_id);
			$parameters = array ();

			if ($project === null) {
				$model->addError('project_id', Yii::t('report', 'Project is unknown.'));
			} else {
				$model->project = $project;
			}
		}

		if (isset ($_POST['EditedReport'])) {
			$model->attributes = $_POST['EditedReport'];

			$report = Report::model()->findByPk($model->report_id);
			if ($report === null) {
				$model->addError('report_id', Yii::t('report', 'Report is unknown.'));
			} else {
				$model->report = $report;
			}

			if ($report !== null) {
				$model->filename = $report->output_filename . '_' . date("Ymd_His", CDateTimeParser::parse($model->edition_date, 'yyyy-MM-dd hh:mm:ss'));
				$model->type = $report->report_type;

				foreach ($report->parameters as $parameter) {
					$p = new EditedReportParameter();
					$p->name = $parameter->name;
					$p->label = $parameter->label;
					$p->type = $parameter->type;
					$p->type_list = $parameter->type_list;
					$p->nullable = $parameter->nullable;
					$parameters[$parameter->name] = $p;
				}
				$model->parameters = $parameters;
			}
				
			$p = Yii::app()->parameter->getParametersArray('RPTTYP');
			$p = $p->toAssociativeArray();
			
			$save = count($model->parameters) == 0 ;
			if (isset ($p[$model->report->report_type])) {
				// Report is based on meeting
				if ($p[$model->report->report_type]["MTG_BASED"])
				{
					$save=($model->meeting_id !== null && $model->meeting_id != "") && $save;
				}
			}
				
			if ($save &&  $model->save())
			{
				if (isset ($_GET['project_id'])) {
					$this->redirect(array (
						'/adviser/printing/list',
						'project_id' => $_GET['project_id']
					));
				} else {
					$this->redirect(array (
						'view',
						'id' => $model->id
					));
				}
			}
		}

		if (isset ($_POST['EditedReportParameter'])) {
			//Constants::print_var($_POST, false);
			//Constants::print_var($_POST['EditedReportParameter'], false);
			foreach ($_POST['EditedReportParameter'] as $p) {
				//Constants::print_var($p, false);
				if (array_key_exists($p['name'], $parameters)) {
					$parameter = $parameters[$p['name']];
					$parameter->attributes = $p;
					$parameters[$p['name']] = $parameter;
				}
			}
			$model->parameters = $parameters;
			if ($model->save()) {
				foreach ($model->parameters as $p) {
					$p->edited_report_id = $model->id;
					$p->report = $model;
					$p->save();
				}

				if (isset ($_GET['project_id'])) {
					$this->redirect(array (
						'/adviser/printing/list',
						'project_id' => $_GET['project_id']
					));
				} else {
					$this->redirect(array (
						'view',
						'id' => $model->id
					));
				}
			}
		}

		$this->render('create', array (
			'model' => $model,
			'parameters' => $parameters
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate() {
		$model = $this->loadModel();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset ($_POST['EditedReport'])) {
			$model->attributes = $_POST['EditedReport'];
			if ($model->save())
			$this->redirect(array (
					'view',
					'id' => $model->id
			));
		}

		$this->render('update', array (
			'model' => $model,

			
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 */
	public function actionDelete() {
		if (Yii::app()->request->isPostRequest) {
			// we only allow deletion via POST request
			$this->loadModel()->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if (!isset ($_GET['ajax']))
			$this->redirect(array (
					'index'
					));
		} else
		throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('EditedReport');
		$this->render('index', array (
			'dataProvider' => $dataProvider,

			
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new EditedReport('search');
		if (isset ($_GET['EditedReport']))
		$model->attributes = $_GET['EditedReport'];

		$this->render('admin', array (
			'model' => $model,

			
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel() {
		if ($this->_model === null) {
			if (isset ($_GET['id']))
			$this->_model = EditedReport::model()->findbyPk($_GET['id']);
			if ($this->_model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset ($_POST['ajax']) && $_POST['ajax'] === 'edited-report-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}